package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.StoreOutRecordIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.entity.UnitOperator;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.*;
import com.wh.wisdomsite.xbox.st.service.IStoreOutRecordService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Map;


/**
 * 出库记录Controller
 *
 * @version V1.0
 * @Package: package com.wh.wisdomsite.xbox.server.controller.st
 * @author: 蔡道行
 * @date: 2018-08-08 10:17
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 **/
@Controller
@RequestMapping(value = "/storeOutRecord")
public class StoreOutRecordController {

    private static final Log logger = LogFactory.getLog(StoreOutRecordController.class);

    @Autowired
    private IStoreOutRecordService iStoreOutRecordService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_storeOutRecord_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/storeOutRecord/storeOutRecordList";
    }

    /**
     * 获取出库记录集合单
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_storeOutRecord_find")
    @RequestMapping(value = "/storeOutRecordList.do")
    public void storeOutRecordList(HttpServletResponse response, StoreOutRecordIn in) {
        try {
            logger.info("加载出库记录单数据列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<StoreOutRecord> page = new Page<StoreOutRecord>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<StoreOutRecord> ewStoreOutRecord = new EntityWrapper<StoreOutRecord>();
            ewStoreOutRecord.setEntity(new StoreOutRecord());
            //根据项目名称查询
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewStoreOutRecord.like("p.prName", in.getPrName());
            }
            //根据合同编号查询
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewStoreOutRecord.like("co.coNumber", in.getCoNumber());
            }
            //根据合同名称查询
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewStoreOutRecord.like("co.coName", in.getCoName());
            }
            //根据出库时间查询
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewStoreOutRecord.between("sor.pullDate", in.getStartDate(), in.getEndDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStartDate())) {
                ewStoreOutRecord.between("sor.pullDate", in.getStartDate(), in.getStartDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getEndDate())) {
                ewStoreOutRecord.between("sor.pullDate", in.getEndDate(), in.getEndDate() + " " + "23:59:59");
            }
            //若用户不是超级管理员根据用户的数据权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewStoreOutRecord = UserUtils.setEntityWrapper(ewStoreOutRecord, "c1", "o1", "p");
            }
            ewStoreOutRecord.groupBy("sor.sameRecord");
            ewStoreOutRecord.orderBy("createDate", false);
            Page<Map<String, Object>> storeOutRecordPage = iStoreOutRecordService.getRecordPage(page, ewStoreOutRecord);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (storeOutRecordPage.getRecords().size() > 0) {
                for (Map<String, Object> storeOutRecord : storeOutRecordPage.getRecords()) {
                    JSONObject object = new JSONObject(storeOutRecord);
                    object.put("pullDate",simpleDateFormat.format(storeOutRecord.get("pullDate")));
                    if(null!=storeOutRecord.get("project")){
                        object.put("prName",((Project) storeOutRecord.get("project")).getPrName());
                        object.put("prLeader",((Project) storeOutRecord.get("project")).getPrLeader());
                    }
                    if(null!=storeOutRecord.get("contract")){
                        object.put("coName",((Contract) storeOutRecord.get("contract")).getCoName());
                        object.put("coNumber",((Contract) storeOutRecord.get("contract")).getCoNumber());
                    }
                    if(null!=storeOutRecord.get("unitOperator")){
                        object.put("uoMgr",((UnitOperator) storeOutRecord.get("unitOperator")).getUoMgr());
                    }
                    array.put(object);
                }
            }
            json.put("total", storeOutRecordPage.getTotal());
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载出库记录单数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载出库记录单数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 页面跳转出库详情列表
     *
     * @return
     */
    @RequiresPermissions("rules:st_storeOutRecord_desc")
    @RequestMapping(value = "toRecordDescList.do", method = RequestMethod.GET)
    public String toRecordDescList(HttpServletRequest request,String sameRecord) {
        request.setAttribute("sameRecord",sameRecord);
        return "/st/storeOutRecord/storeOutRecordDescList";
    }

    /**
     * 获取出库记录详情集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_storeOutRecord_desc")
    @RequestMapping(value = "/storeOutRecordDescList.do")
    public void storeOutRecordDescList(HttpServletResponse response, StoreOutRecordIn in) {
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        try {
            logger.info("加载出库记录详情数据列表-->>开始");
            Integer total= 0;
            if (StringUtils.isNotEmpty(in.getSameRecord())) {
                //设置分页
                if (in.getPage() == 0) in.setPage(1);
                if (in.getRows() == 0) in.setRows(10);
                Page<StoreOutRecord> page = new Page<StoreOutRecord>();
                page.setCurrent(in.getPage());
                page.setSize(in.getRows());
                //设置条件
                EntityWrapper<StoreOutRecord> ewStoreOutRecord = new EntityWrapper<StoreOutRecord>();
                ewStoreOutRecord.setEntity(new StoreOutRecord());
                //统一入库标识
                ewStoreOutRecord.eq("sor.sameRecord", in.getSameRecord());
                //根据材料名称查询
                if (StringUtils.isNotEmpty(in.getMaterialName())) {
                    ewStoreOutRecord.like("ma.materialName", in.getMaterialName());
                }
                //根据材料规格查询
                if (StringUtils.isNotEmpty(in.getStandardType())) {
                    ewStoreOutRecord.like("ma.standardType", in.getStandardType());
                }
                ewStoreOutRecord.orderBy("sor.createDate", false);
                Page<Map<String, Object>> storeOutRecordPage = iStoreOutRecordService.getMapsPage(page, ewStoreOutRecord);
                if (storeOutRecordPage.getRecords().size() > 0) {
                    for (Map<String, Object> storeOutRecord : storeOutRecordPage.getRecords()) {
                        JSONObject object = new JSONObject(storeOutRecord);
                        object.put("pullDate",simpleDateFormat.format(storeOutRecord.get("pullDate")));
                        if(null!=storeOutRecord.get("supplier")){
                            object.put("supId",((Supplier) storeOutRecord.get("supId")).getSupId());
                            object.put("supName",((Supplier) storeOutRecord.get("supName")).getSupName());
                        }
                        if(null!=storeOutRecord.get("material")){
                            object.put("materialName",((Material)storeOutRecord.get("material")).getMaterialName());
                            object.put("standardType",((Material)storeOutRecord.get("material")).getStandardType());
                            object.put("meteringUnit",((Material)storeOutRecord.get("material")).getMeteringUnit());
                        }
                        array.put(object);
                    }
                }
                total = storeOutRecordPage.getTotal();
            }
            json.put("total", total);
            json.put("rows", array);
            ResManager.getTextOut(response).print(json);
            logger.info("加载出库记录详情数据列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载出库记录详情数据列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 出库记录详情
     *
     * @param storeOutRecordIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:st_storeOutRecord_view")
    @RequestMapping("/storeOutRecordDesc.do")
    public String storeOutRecordDesc(StoreOutRecordIn storeOutRecordIn, HttpServletRequest request) {
        try {
            logger.info("出库记录详情-->>开始");
            Map<String, Object> storeOutRecord = iStoreOutRecordService.getMapById(storeOutRecordIn.getStorId());
            if (storeOutRecord.get("createBy") != null) {
                storeOutRecord.put("createBy", UserMapManager.getUserLoginNameInMap(storeOutRecord.get("createBy").toString()));
            }
            if (storeOutRecord.get("purchaseDetail") != null) {
                storeOutRecord.put("reqPerson", UserMapManager.getUserLoginNameInMap(((PurchaseDetail)storeOutRecord.get("purchaseDetail")).getReqPerson()));
            }
            if (storeOutRecord.get("updateBy") != null) {
                storeOutRecord.put("updateBy", UserMapManager.getUserLoginNameInMap(storeOutRecord.get("updateBy").toString()));
            }
            request.setAttribute("storeOutRecord", storeOutRecord);
            logger.info("出库记录详情-->>结束");
        } catch (Exception e) {
            logger.debug("出库记录详情-->>Exception" + e.getMessage());
            e.printStackTrace();
        }
        return "/st/storeOutRecord/storeOutRecordDesc";
    }
}
